from .visitorbase import Element, Visitor

from ...hrunutils import strStrip, checkStr2Int_Bool

"""
字段类型

字段行的类型：
    bool        ------------Boolean   1
    字符串         
    stringarray ------------    >=1
    eq:[k,v]    ----------- :[   validates  list   >=1
    k：v        ------------ :   >=1
    json        -------------{}   >=1
    


"""
Line_Bool = 'bool'
Line_String = 'string'
Line_Validate = 'validate'
Line_KeyValue = 'kvalue'
Line_Json = 'json'


class Line(Element):

    def __init__(self, value):
        self.lineString = value

    @property
    def type(self):
        pass


class Lines(Element):

    def __init__(self, field):
        self.lines = str(field.value).splitlines()

    def iter(self):
        return self.lines

    def __str__(self):
        return str(self.lines)

    def count(self):
        return len(self.lines)


class ValueMixin:
    def _parserFields2Dict(self, listfields, listvalues):
        dict_fields = {}

        def mergeRequest(sfield, svalue, dict_request={}):
            # 合并 request字段到 dict_request
            dict_request[sfield.split('.')[1]] = svalue
            return dict_request

        for icol in range(1, len(listfields)):  # 遍历字段
            xfield = listfields[icol]  # 字段名
            svalue = listvalues[icol]  # 字段值

            if svalue == '':  # 如果为空行即跳过
                pass
            else:
                # field 需要解析value
                if xfield in ['variables', 'parameters',
                              'request.params', 'request.data']:
                    svalue = self.parserValueToDict(svalue)
                elif xfield in ['request.json']:
                    # json 兼容
                    if svalue.startswith('{'):
                        svalue = eval(svalue)
                    else:
                        svalue = self.parserValueToDict(svalue)
                elif xfield in ['request.headers', 'headers']:
                    # 值为 string 类型
                    svalue = self.parserValueToDict(svalue, value2string=True)
                elif xfield in ['extract', 'validate']:
                    # list格式类型
                    svalue = self.parserValue2List(svalue)
                elif xfield in ['verify', 'skiped', 'skip']:
                    # 解析verify false\true
                    svalue = False if svalue == 0 else True
                elif xfield in ['output']:
                    svalue = self.parserValue2ArrayList(svalue)
                elif xfield == 'testcase':
                    # 处理 testcase 对应的sheet   =   testcase_def
                    dict_fields['testcase_def'] = self.fromSheet2List(self.workBook.sheet_by_name(svalue))[0]

                if xfield.startswith('request'):
                    # 合并request字段为 dict
                    dict_fields['request'] = mergeRequest(xfield, svalue)
                else:
                    dict_fields[xfield] = svalue
        return dict_fields

    def parserValue2List(self, svalue):
        valist = []
        tmplist = svalue.splitlines()
        i = 0
        while (i < len(tmplist)):
            s = tmplist[i]
            skey, svalue = self.parserValue2KeyValue(s.strip())

            if svalue == '':  # 处理多行value
                pass
            else:
                valist.append({skey: self.parserKvalue(svalue)})

            i += 1

        return valist

    def parserValue2ArrayList(self, svalue):
        return svalue.splitlines()

    def parserMultiLineToList(self, slist, index=0):
        tlist = []
        for i in range(index, len(slist)):
            tlist.append(self.parserKvalue(strStrip(slist[i])))
        return tlist

    def parserKvalue(self, svalue, value2string=False):
        if svalue.startswith('['):
            svalue = svalue.replace('[', '').replace(']', '').strip()

            if svalue.startswith('{'):  # 解析dict
                return eval(svalue)

            xlist = svalue.split(',', 1)
            # tlist =[str(self.strip(s)) for s in xlist]
            # for s in xlist:
            #     tlist.append(self.strip(s) )

            return [checkStr2Int_Bool(s) for s in xlist]
        else:
            return checkStr2Int_Bool(svalue) if not value2string else svalue.strip()

    def parserValueToDict(self, svalue, value2string=False):
        tmpdict = {}
        tmplist = svalue.splitlines()

        i = 0
        while (i < len(tmplist)):
            s = tmplist[i]
            if s != '':  # 空行跳过
                skey, svalue = self.parserValue2KeyValue(s.strip())

                if svalue == '':  # 处理多行value
                    tmpdict[skey.strip()] = self.parserMultiLineToList(tmplist, i + 1)
                    break
                else:
                    tmpdict[skey.strip()] = self.parserKvalue(svalue, value2string)
            i += 1

        return tmpdict

    def parserValue2KeyValue(self, svalue):
        """
        转化 key:value 为两个变量
        :param svalue:
        :return:  返回key、value 两个变量参数
        """
        xkeyvalue = svalue.split(':', 1)
        xkey = strStrip(xkeyvalue[0])
        return xkey, xkeyvalue[1].strip() if len(xkeyvalue) == 2 else ''


class LinesVisitor(Visitor, ValueMixin):

    def __init__(self, field):
        self.field = field
        self.lines = Lines(field)

    def visit(self, element=None):
        return self.visitByName(self.field.value)

    # def scanLines(self):
    #     # for l in Lines(linestr).iter():
    #     #     Line(l).accept(self)
    #
    #     # xlines = Lines(linestr)
    #     return self.visitByName(self.field.value)

    def get_meth_name(self, element):
        return 'parser_' + self.field.type

    def parser_string(self, element):
        return str(element)

    def parser_dict(self, element):
        return self.parserValueToDict(element)

    def parser_dictstr(self, element):
        # 值为 string 类型
        return self.parserValueToDict(element, value2string=True)

    def parser_list(self, element):
        # list格式类型
        return self.parserValue2List(element)

    def parser_json(self, element):
        # json 兼容
        if element.startswith('{'):
            return eval(element)

        return self.parser_dict(element)

    def parser_bool(self, element):
        # 解析verify false\true
        return False if element == 0 else True

    def parser_skip(self, element):
        # 解析verify false\true
        return False if element == 0 else True

    def parser_array(self, element):
        return self.parserValue2ArrayList(element)

    def parser_sheet(self, element):
        # 读取testcase 的sheetname，并转化为 testcase_def

        from .vexcel import ExcelVisitor
        ev = ExcelVisitor()

        return ev.scansheet_json(element)



